import { defineStore } from 'pinia'
import type { RouteRecordName } from 'vue-router'
import { useUserStore } from '@/stores/userStore'
import { toTree } from '@/tools/tree'
import http from '@/tools/http'

interface MenuStore {
  menuList: Menu[]
  breadcrumbList: string[]
}

interface Menu {
  menuCode: string
  menuName?: string
  menuStatus?: string
  menuType?: string
  loadType?: string
  menuUrl?: string
  menuIcon?: string
  menuSort?: number
  menuParent?: string
  remark?: string
}

export const useMenuStore = defineStore('menu', {
  state: (): MenuStore => ({
    menuList: [],
    breadcrumbList: []
  }),
  getters: {
    menuTree: (state) => {
      return () => toTree(state.menuList.filter(menu => menu.menuStatus === '0'), "menuParent", null, "menuCode", "menuName", "menuCode")
    },
    menuName: (state) => {
      return (menuCode: string | RouteRecordName | undefined) => {
        if (menuCode && menuCode === "home") {
          return "首页"
        }
        if (menuCode && menuCode === "no-auth") {
          return "无权限"
        }
        if (state.menuList) {
          for (let i = 0; i < state.menuList.length; i++) {
            if (state.menuList[i].menuCode === menuCode) {
              return state.menuList[i].menuName
            }
          }
        }
        return null
      }
    }
  },
  actions: {
    refreshBreadcrumbList(breadcrumbList: string[]) {
      this.breadcrumbList = breadcrumbList
    },
    refreshMenuList(menuList: Menu[]) {
      const userStore = useUserStore()
      this.menuList = menuList.filter((item: Menu) => userStore.hasAuth(item.menuCode))
    },
    initMenuList() {
      const userStore = useUserStore()
      http.post("/menu/list").then(({ data }) => {
        if (data.code === "0") {
          const whiteList: string[] = [
            "login",
            "user-info",
            "user-message",
            "revise-pwd",
            "home",
            "no-auth"
          ]
          this.menuList = data.data.filter((item: Menu) => {
            if (whiteList.includes(item.menuCode)) {
              return true
            }
            return item.menuType !== '2' && userStore.hasAuth(item.menuCode)
          })
        }
      })
    },
    clear() {
      this.breadcrumbList.length = 0
      this.menuList.length = 0
    }
  }
})